package com.sskj.b70.v.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bulong.rudeness.RudenessScreenHelper;
import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.adapter.ItemClickSupport;
import com.sskj.b70.adapter.slimadapter.IViewInjector;
import com.sskj.b70.adapter.slimadapter.SlimAdapter;
import com.sskj.b70.adapter.slimadapter.SlimInjector;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.decoration.DividerLineItemDecoration;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.RxBusCode;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.m.bean.UserInfo;
import com.sskj.b70.p.activity.MinePresenter;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.SPUtils;
import com.sskj.b70.utils.TipUtil;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.activity.AboutUsActivity;
import com.sskj.b70.v.activity.AgentPersonActivity;
import com.sskj.b70.v.activity.ApplyAgentPersonActivity;
import com.sskj.b70.v.activity.AssetManageActivity;
import com.sskj.b70.v.activity.BindMobileActivity;
import com.sskj.b70.v.activity.CashAddressListActivity;
import com.sskj.b70.v.activity.DagListActivity;
import com.sskj.b70.v.activity.InforMationActivity;
import com.sskj.b70.v.activity.LoginActivity;
import com.sskj.b70.v.activity.MainActivity;
import com.sskj.b70.v.activity.PersonalActivity;
import com.sskj.b70.v.activity.SecurityCenterActivity;
import com.sskj.b70.v.base.BaseFragment;

import java.util.ArrayList;

import butterknife.BindView;


/**
 * Created by Lee on 2018/2/28 0028.
 */

public class MineFragment extends BaseFragment<MainActivity, MinePresenter> {


    @BindView(R.id.ivTitleHead)
    ImageView ivTitleHead;
    @BindView(R.id.ivExit)
    ImageView ivExit;
    @BindView(R.id.tvMoney)
    TextView tvMoney;
    @BindView(R.id.tvAccount)
    TextView tvAccount;
    @BindView(R.id.tvLogin)
    TextView tvLogin;
    @BindView(R.id.llLogin)
    LinearLayout llLogin;
    @BindView(R.id.llNoLogin)
    LinearLayout llNoLogin;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private MaterialDialog tip;
    private int applyStatus;
    private AlertDialog tipDialog;
    private AlertDialog tipErrorDialog;
    private Object applyRefuseReason;
    private Dialog loginDialog;


    public class TitleBean {
        String title;
        int res;
        Class clazz;

        public TitleBean(String title, int res, Class clazz) {
            this.clazz = clazz;
            this.title = title;
            this.res = res;
        }

        public Class getClazz() {
            return clazz;
        }

        public void setClazz(Class clazz) {
            this.clazz = clazz;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getRes() {
            return res;
        }

        public void setRes(int res) {
            this.res = res;
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getUser();
        }
    }

    private void getUser() {
        if (MyAppLication.isLogin()) {
            if (mPresenter != null) {
                mPresenter.requestUserInfo();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            getUser();
        }
    }

    @Override
    public void initView() {
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
        ClickUtil.click(tvLogin, () -> startActivity(new Intent(getActivity(), LoginActivity.class)));
        ClickUtil.click(ivExit, () -> {
            if (tip == null) {
                tip = TipUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.strMineFragment0), this::logout);
            }
            tip.show();
        });
        ArrayList<TitleBean> titleBeans = new ArrayList<>();
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment1), R.mipmap.icon_me_personal, PersonalActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment2), R.mipmap.icon_security_center, SecurityCenterActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment3), R.mipmap.icon_recharge, AssetManageActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment4), R.mipmap.icon_mine_dag_detail, DagListActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment5), R.mipmap.icon_address_gray, CashAddressListActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment6), R.mipmap.icon_invite_friend, AgentPersonActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment7), R.mipmap.zi_xun, InforMationActivity.class));
        titleBeans.add(new TitleBean(App.INSTANCE.getString(R.string.strMineFragment8), R.mipmap.icon_about_us, AboutUsActivity.class));

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setDividerColor(ContextCompat.getColor(getActivity(), R.color.line_color))
                .setLeftPadding((int) RudenessScreenHelper.pt2px(getActivity(), 50))
                .setRightPadding((int) RudenessScreenHelper.pt2px(getActivity(), 50))
                .setLastDraw(false)
        );
        SlimAdapter<TitleBean> slimAdapter = SlimAdapter.create().register(R.layout.recy_item_mine, new SlimInjector<TitleBean>() {
            @Override
            public void onInject(TitleBean data, IViewInjector injector) {
                injector.text(R.id.tv_title, data.getTitle())
                        .image(R.id.iv_title, data.getRes());
            }
        }).attachTo(recyclerView).updateData(titleBeans);
        ItemClickSupport.addTo(recyclerView).setOnItemClickListener((recyclerView, position, v) -> {
            switch (position) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    if (MyAppLication.isLogin()) {
                        if (position == 5) {
                            if (!checkPhone()) {
                                return;
                            }
                            switch (mActivity.mUserInfo.getIs_apply()) {
                                case 1:  // 未申请
//                                    showApplyTip();
                                    ApplyAgentPersonActivity.start(getActivity());
                                    break;
                                case 2:
                                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strMineFragment9));
                                    break;
                                case 3:
                                    AgentPersonActivity.start(getActivity());
                                    break;
                                case 4:   // 已拒绝
                                    showReApplyTip();
                                    break;
                            }
                        } else {
                            if (position != 1 && !checkPhone()) {
                                return;
                            }
                            startActivity(new Intent(mActivity, slimAdapter.getDataItem(position).getClazz()));
                        }
                    } else {
                        showLoginDialog();
                    }
                    break;
                case 6:
                case 7:
                    startActivity(new Intent(mActivity, slimAdapter.getDataItem(position).getClazz()));
                    break;
            }

        });
        getUser();
    }

    public boolean checkPhone() {
        if (TextUtils.isEmpty(MyAppLication.getMobile())) {
            ToastUtil.showShort(getString(R.string.mine_bind_phone));
            BindMobileActivity.start(getActivity());
            return false;
        }
        return true;
    }


    /**
     * 显示登录对话框
     */
    private void showLoginDialog() {
        if (loginDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View v = inflater.inflate(R.layout.dialog_about_us_tip, null);
            TextView cancle = v.findViewById(R.id.tv_cancel);
            TextView tvTitle = v.findViewById(R.id.tv_title);
            TextView copy = v.findViewById(R.id.tv_copy);
            TextView email = v.findViewById(R.id.tv_email);
            cancle.setText(App.INSTANCE.getString(R.string.strMineFragment10));
            copy.setText(App.INSTANCE.getString(R.string.strMineFragment11));
            tvTitle.setText(App.INSTANCE.getString(R.string.strMineFragment12));
            email.setText(App.INSTANCE.getString(R.string.strMineFragment13));
            loginDialog = builder.create();
            loginDialog.show();
            loginDialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
            ClickUtil.click(cancle, () -> loginDialog.dismiss());
            ClickUtil.click(copy, () -> {
                loginDialog.dismiss();
                startActivity(new Intent(mActivity, LoginActivity.class));
            });
        } else {
            loginDialog.show();
        }
    }

    /**
     * 显示经纪人申请跳转提示
     */
    private void showApplyTip() {
        if (tipDialog == null) {
            tipDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(App.INSTANCE.getString(R.string.strMineFragment14))
                    .setMessage(App.INSTANCE.getString(R.string.strMineFragment15))
                    .setPositiveButton(App.INSTANCE.getString(R.string.strMineFragment16), (dialog, which) -> {
                        dialog.dismiss();
                        ApplyAgentPersonActivity.start(getActivity());
                    })
                    .setNegativeButton(App.INSTANCE.getString(R.string.strMineFragment10), (dialog, which) -> dialog.dismiss()).create();
        }
        tipDialog.show();
    }

    /**
     * 显示经纪人重新申请跳转提示
     */
    private void showReApplyTip() {
        tipErrorDialog = new AlertDialog.Builder(getActivity())
                .setTitle(App.INSTANCE.getString(R.string.strMineFragment18))
                .setMessage(App.INSTANCE.getString(R.string.strMineFragment19) + applyRefuseReason)
                .setPositiveButton(App.INSTANCE.getString(R.string.strMineFragment20), (dialog, which) -> {
                    dialog.dismiss();
                    ApplyAgentPersonActivity.start(getActivity());
                })
                .setNegativeButton(App.INSTANCE.getString(R.string.strMineFragment10), (dialog, which) -> dialog.dismiss()).create();
        tipErrorDialog.show();
    }

    public void updateUserTitle(UserInfo user) {
        if (mActivity != null) {
            SPUtils.putBean(mActivity, Constants.SP_USER_INFO, user);
            loginSuccess(user);
        }
    }

    private void loginSuccess(UserInfo user) {
        if (llNoLogin != null) {
            llLogin.setVisibility(View.VISIBLE);
            llNoLogin.setVisibility(View.GONE);
            applyStatus = user.getIs_apply();
            applyRefuseReason = user.getApply_reason();
            if (TextUtils.isEmpty(user.getMobile())) {
                tvAccount.setText(user.getEmail());
            } else {
                String start = user.getAccount().substring(0, 3);
                String end = user.getAccount().substring(7, 11);
                tvAccount.setText(start + "****" + end);
            }
            tvMoney.setText(user.getWallone());
        }
    }

    @Subscribe(code = Constants.USER_LOGOUT, threadMode = ThreadMode.MAIN)
    public void logout() {
        SPUtils.clear();
        MyAppLication.getApplication().removeAllHttpParam();
        llLogin.setVisibility(View.GONE);
        llNoLogin.setVisibility(View.VISIBLE);
        mActivity.mUserInfo = null;

    }

    @Subscribe(code = RxBusCode.USER_INFO_UPDATE, threadMode = ThreadMode.MAIN)
    public void updateUser() {
        mPresenter.requestUserInfo();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
